﻿using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
using System.Reflection;

namespace RuoVea.ExSwagger;

/// <summary>
/// 
/// </summary>
public class SwaggerApi : IDocumentFilter
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="swaggerDoc"></param>
    /// <param name="context"></param>
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        foreach (ApiDescription description in context.ApiDescriptions)
        {
            if (description.TryGetMethodInfo(out MethodInfo method))
            {
                if (method.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenAttribute)) || method.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenAttribute)))
                {
                    string key = "/" + description.RelativePath;
                    if (key.Contains("?"))
                    {
                        int idx = key.IndexOf("?", System.StringComparison.Ordinal);
                        key = key.Substring(0, idx);
                    }
                    swaggerDoc.Paths.Remove(key);
                }
            }
        }
    }
}
